package top.starmc.starpet.config

import eos.moe.dragoncore.api.CoreAPI
import taboolib.common.LifeCycle
import taboolib.common.platform.Awake
import taboolib.common.platform.function.releaseResourceFile
import taboolib.module.configuration.Config
import taboolib.module.configuration.ConfigFile
import top.starmc.starpet.internal.DevelopData
import top.starmc.starpet.internal.PetData
import java.text.DecimalFormat

object Config {
    @Config("config.yml")
    lateinit var config: ConfigFile

    @Config("internal.yml")
    lateinit var internal: ConfigFile

    @Config("develop.yml")
    lateinit var develop: ConfigFile

    val numberFormat by lazy { DecimalFormat(config.getString("number-format")) }

    var rpgPlugin = 0

    lateinit var equipSlot: String

    lateinit var callKey: String

    @JvmStatic
    var followDistance = 3.0

    @JvmStatic
    var teleportDistance = 10.0

    lateinit var mysql: MySQL

    val internalMap = hashMapOf<String, PetData>()

    val developList = mutableListOf<DevelopData>()

    @Awake(LifeCycle.ENABLE)
    fun loadConfig() {
        internalMap.clear()
        developList.clear()

        releaseResourceFile("config.yml")
        config.reload()
        releaseResourceFile("internal.yml")
        internal.reload()
        releaseResourceFile("develop.yml")
        develop.reload()

        rpgPlugin = config.getInt("rpg-plugin")
        equipSlot = config.getString("equip-slot")!!
        callKey = config.getString("call-key")!!.also {
            CoreAPI.registerKey(it)
        }
        followDistance = config.getDouble("follow-distance").let {
            it * it
        }
        teleportDistance = config.getDouble("teleport-distance").let {
            it * it
        }
        if (config.getBoolean("database.enable") && !useSQL()) {
            mysql = MySQL(config)
        }

        internal.getKeys(false).forEach {
            internalMap[it] = PetData(internal.getConfigurationSection(it)!!)
        }

        develop.getKeys(false).forEach {
            developList += DevelopData(develop.getConfigurationSection(it)!!)
        }
    }

    @JvmStatic
    fun useSQL(): Boolean {
        return ::mysql.isInitialized
    }
}